<template>
    <div id="contianer">
        <div class="mapPage">
            <!-- <div class="button_tab">
                <el-button @click="">返回</el-button
                ><el-button type="primary" @click="">保存</el-button>
            </div>
            <hr style="border-top: 1px solid #d8d8d8" /> -->
            <div class="main">
                <div class="file_box">
                    <div id="video" v-if=" $route.query.row.fileType == 38">
                      <div class="video_btn_img" v-if="tag_time_list && tag_time_list.length > 0">
                        <div class="tag_time" v-for="(item, index) in tag_time_list" :key="'tag_time'+index" v-if="tag_time_index === index">
                          <img src="@/assets/images/prev.svg" alt="" :class="tag_time_index === 0?'disabled':''" @click="handlePrev(item, index)">
                          <img src="@/assets/images/next.svg" alt="" :class="tag_time_index === (tag_time_list.length - 1)?'disabled':''" @click="handleNext(item, index)">
                        </div>
                      </div>
                    </div>
                    <iframe
                        id="iframe"
                        v-else
                        ref="iframe"
                        src=""
                        frameborder="0"
                        width="100%"
                        height="100%"
                    ></iframe>
                </div>

<!--                <div
                    class="video_text_box"
                    v-if="
                        $route.query.row.videoType &&
                        $route.query.row.videoType === 1
                    "
                >
                    <el-card
                        class="box-card"
                        v-for="(item, index) in analysisData.content"
                        :key="index"
                    >
                        <div slot="header" class="clearfix">
                            <span
                                >时间段：{{ item.seg_time[0] }} 秒 &#45;&#45;
                                {{ item.seg_time[1] }} 秒</span
                            >
                        </div>
                        <div class="text item">
                            <el-input
                                type="textarea"
                                placeholder="请输入内容"
                                v-model="item.text"
                                :autosize="{ minRows: 2 }"
                            ></el-input>
                        </div>
                    </el-card>
                </div>-->

                <div class="tag_box">
                    <h2>
                        <span>标签列表</span
                        ><el-button type="primary" size="small" @click="addTag"
                            >新增标签</el-button
                        >
                    </h2>
                    <div class="tag_list">
                      <el-tag
                        v-for="tag in tags"
                        closable
                        :key="tag.id"
                        class="tag_item"
                        :class="tag.id === activeTag.id ? 'tag_active' : ''"
                        @click="handleTag(tag)"
                        @close="delTag(tag.id)"
                      >
                          {{ tag.labelName }}
                      </el-tag>
                    </div>
                </div>
            </div>

            <el-button type="primary" style="margin-top:10px;margin-left: 50%;
    transform: translateX(-50%);" @click="sureUpdate">确定更新</el-button>
        </div>
        <!-- 新增标签 -->
        <el-dialog
            :title="elementsTitle"
            :visible.sync="elementsVisible"
            :close-on-click-modal="false"
            width="30%"
            center
        >
            <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                label-width="120px"
            >
                <el-form-item label="标签类型" prop="labelLevel">
                    <el-select
                        v-model="ruleForm.labelLevel"
                        placeholder="请选择标签类型"
                        disabled
                    >
                        <el-option
                            v-for="item in labelOptionList"
                            :key="item.value"
                            :value="item.value"
                            :label="item.label"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上级领域标签" prop="area">
                    <el-select
                        v-model="ruleForm.area"
                        placeholder="请选择上级领域标签"
                        @change="changeArea"
                    >
                        <el-option
                            v-for="item in areaList"
                            :key="item.id"
                            :value="item.id"
                            :label="item.labelName"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上级岗位标签" prop="post">
                    <el-select
                        v-model="ruleForm.post"
                        placeholder="请选择上级岗位标签"

                    >
                        <el-option
                            v-for="item in postList"
                            :key="item.id"
                            :value="item.id"
                            :label="item.labelName"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="标签名称" prop="labelName">
                    <el-autocomplete
                    clear
                        v-model="ruleForm.labelName"
                        ref="labelNameRef"
                        :fetch-suggestions="querySearchAsync"
                        placeholder="请输入标签名称"
                        :disabled="!ruleForm.area || !ruleForm.post"
                        @select="handleSelect"
                    ></el-autocomplete>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="elementsConfirm"
                    >确 定</el-button
                >
                <el-button @click="elementsVisibleClose">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
  data() {
    return {
      elementsTitle: '新增标签',
      elementsVisible: false,
      areaList: [],
      postList: [],
      ruleForm: {
        labelLevel: '标签元素',
        labelName: '',
        area: '',
        post: ''
      },
      rules: {
        labelName: [
          { required: true, message: '请输入标签名称', trigger: 'change' }
        ],
        area: [
          { required: true, message: '请选择上级领域标签', trigger: 'change' }
        ],
        post: [
          { required: true, message: '请选择上级岗位标签', trigger: 'change' }
        ]
      },
      tags: [],
      activeTag: {},
      downloadUrl: '',
      labelOptionList: [
        {
          label: '领域标签',
          value: 1
        },
        {
          label: '岗位标签',
          value: 2
        },
        {
          label: '标签元素',
          value: 3
        }
      ],
      timeout: null,
      isNew: true,
      selectedLabel: -1,
      analysisData: {},
      player: Object,
      tag_time_list: [],
      tag_time: 0,
      tag_time_index: 0,
      dataInfo: null
    }
  },
  components: {},
  mounted() {
    this.detailFn()
  },
  methods: {
    detailFn() {
      const row = this.$route.query.row
      this.dataInfo = row
      this.labelListFn(row)
      if (row.fileType == 38) {
        // 培训视频类型，0-课件，1-视频
        this.$http({
          url: '/knowledgeData/video/verification',
          method: 'get',
          params: {
            id: row.id
          }
        }).then(({ data }) => {
          this.analysisData = JSON.parse(data.data.videoJson)
          console.log(this.analysisData, '4444')
        })
        this.$http({
          url: '/knowledgeData/release/preview',
          method: 'get',
          params: {
            id: row.id
          }
        }).then(({ data }) => {
          console.log('获取文件之后地址', data.data.downloadUrl)
          this.previewVideoVisible = true
          setTimeout(() => {
            this.player = new this.$Player({
              id: 'video', // 元素id
              lang: 'zh', // 设置中文
              volume: 0, // 默认静音
              autoplay: false, // 自动播放
              screenShot: false, // 开启截图功能
              // 视频地址
              url: this.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl,
              // 封面图
              // poster:'',
              fluid: true, // 填满屏幕 （流式布局）
              playbackRate: [0.5, 0.75, 1, 1.5, 2] // 传入倍速可选数组
            })
          }, 300)
        })
      } else {
        this.$http({
          url: '/knowledgeData/verification',
          method: 'get',
          params: {
            id: row.id
          }
        }).then(({ data }) => {
          console.log('原始文件地址', data)
          this.parsingFiles(
            [['token', +localStorage.getItem('token')]],
            this.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl
          )
        })
        this.$http({
          url: '/knowledgeData/release/preview',
          method: 'get',
          params: {
            id: row.id
          }
        }).then(({ data }) => {
          console.log('获取文件之后地址', data.data.downloadUrl)
          this.downloadUrl = this.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl
          this.previewVisible = true

          setTimeout(() => {
            var iframe = document.querySelector('#iframe')
            this.populateIframe(
              iframe,
              [['token', +localStorage.getItem('token')]],
              this.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl
            )
          }, 0)
        })
      }
    },
    // 确定更新操作
    sureUpdate(){
      this.$http({
        url:'/knowledgeData/updateLabel',
        method:"post",
        data:{
          id:this.$route.query.row.id
        }
      }).then(()=>{
        this.$message.success("更新成功")
        // this.$router.push('/knowledgeLabels')
        this.$tab.closePage();
      })
    },
    populateIframe(iframe, headers, url) {
      var xhr = new XMLHttpRequest()
      xhr.open('GET', url)
      xhr.responseType = 'blob'
      headers.forEach((header) => {
        xhr.setRequestHeader(header[0], header[1])
      })
      // xhr.setRequestHeader("X-Amz-Server-Side-Encryption-Customer-Key-MD5", "m7AXuOLSaEQc1369IHCZGw==")
      // xhr.setRequestHeader("X-Amz-Server-Side-Encryption-Customer-Algorithm", "AES256")
      // xhr.setRequestHeader("X-Amz-Server-Side-Encryption-Customer-Key", "5svVq6aMjTLMBTD0yaIT9u735QnpHteabx6nFZUXvac=")
      xhr.onreadystatechange = () => {
        if (xhr.readyState === xhr.DONE) {
          if (xhr.status === 200) {
            console.log(URL.createObjectURL(xhr.response), 'ffff')
            this.previewUrl = URL.createObjectURL(xhr.response)
            console.log(
              '预览地址',
              URL.createObjectURL(xhr.response),
              this.activeTag
            )
            iframe.src =
              './static/pdfjs/web/viewer.html?keyword=' +
              this.activeTag.labelName +
              '&file=' +
              URL.createObjectURL(xhr.response)
          }
        }
      }
      xhr.send()
    },
    parsingFiles(headers, url) {
      var xhr = new XMLHttpRequest()
      xhr.open('GET', url)
      xhr.responseType = 'blob'
      headers.forEach((header) => {
        xhr.setRequestHeader(header[0], header[1])
      })

      xhr.onreadystatechange = async() => {
        if (xhr.readyState === xhr.DONE) {
          if (xhr.status === 200) {
            const blobUrl = URL.createObjectURL(xhr.response)
            console.log('预览地址', URL.createObjectURL(xhr.response))
            // 获取Blob URL的内容
            const response = await fetch(blobUrl)
            const text = await response.text()
            // 转换为HTML字符串
            this.html = text
            // 清理URL对象URL.revokeObjectURL(blobUrl);
            URL.revokeObjectURL(blobUrl)
          }
        }
      }
      xhr.send()
    },
    // 获取标签列表
    labelListFn(row) {
      this.$http({
        url: '/knowledgeLabel/knowledgeLabelList',
        method: 'GET',
        params: {
          knowledgeId: row.id
        }
      }).then(({ data }) => {
        this.tags = data.data
      })
    },
    // 添加标签
    addTag() {
      this.elementsTitle = '新增标签'
      this.getAreaData()
      this.elementsVisible = true
      this.$refs['ruleForm'] && this.$refs['ruleForm'].resetFields()
      this.selectedLabel = -1
    },
    changeArea() {
      this.ruleForm.post = ''
      this.getPostData()
    },
    async querySearchAsync(queryString, cb) {
      this.isNew = true
      const params = {
        parentId: this.ruleForm.post.toString(),
        name: queryString
      }
      const nickNameList = []
      const res = await this.$http({
        url: '/knowledgeLabel/fuzzySearch',
        method: 'get',
        params
      })
      console.log(res, 'res')
      if (res.data.code === 200) {
        if (res.data.data && res.data.data.length === 0) {
          nickNameList.push({
            value: '无匹配结果',
            id: -1
          })
          cb(nickNameList)
        } else {
          res.data.data.forEach((item) => {
            nickNameList.push({
              value: item.labelName,
              id: item.id
            })
          })
          clearTimeout(this.timeout)
          this.timeout = setTimeout(() => {
            cb(nickNameList)
          })
        }
      }
    },
    handleSelect(item) {
      this.isNew = false
      if (item.id !== -1) {
        this.selectedLabel = item.id
      }
    },
    getAreaData() {
      this.$http({
        url: '/knowledgeLabel/field',
        method: 'get',
        params: {}
      }).then(({ data }) => {
        if (data.code == 200) {
          this.areaList = data.data
        }
      })
    },
    getPostData() {
      this.$http({
        url: '/knowledgeLabel/post',
        method: 'get',
        params: {
          name: '',
          parentId: this.ruleForm.area
        }
      }).then(({ data }) => {
        if (data.code == 200) {
          this.postList = data.data
        }
      })
    },
    elementsVisibleClose() {
      this.elementsVisible = false
    },
    elementsConfirm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: '/knowledgeLabel/checkBind',
            method: 'get',
            params: {
              knowledgeId: this.$route.query.row.id,
              name: this.ruleForm.labelName
            }
          }).then(({ data }) => {
            if (data.data) {
              const labelList = this.tags.map((o) => {
                return o.id
              })
              if (this.isNew) {
                this.$http({
                  url: '/knowledgeLabel/add',
                  method: 'post',
                  data: {
                    labelLevel: 3,
                    labelName: this.ruleForm.labelName,
                    labelType: '标签元素',
                    parentIds: this.ruleForm.post
                  }
                }).then(({ data }) => {
                  if (data.code == 200) {
                    this.elementsVisible = false
                    this.$message.success('新增标签成功')
                    data.data.ids && labelList.push(data.data.ids)
                    this.bindLabel(labelList)
                  } else {
                    this.$message.warning(data.msg)
                  }
                })
              } else {
                this.elementsVisible = false
                labelList.push(this.selectedLabel)
                this.bindLabel(labelList)
              }
            } else {
              this.$message.error('文件中不存在该关键字')
            }
          })
        }
      })
    },
    bindLabel(labelList) {
      this.$http({
        url: '/knowledgeLabel/bind',
        method: 'post',
        data: {
          knowledgeId: this.$route.query.row.id,
          labelList: labelList
        }
      }).then(({ data }) => {
        if (data.code == 200) {
          this.labelListFn(this.dataInfo)
        }
      })
    },
    handleTag(tag) {
      if (tag.id === this.activeTag.id) {
        this.$set(this.activeTag, 'id', '')
        this.$set(this.activeTag, 'labelName', '')
      } else {
        this.$set(this.activeTag, 'id', tag.id)
        this.$set(this.activeTag, 'labelName', tag.labelName)
      }
      if (this.dataInfo.fileType == "38") {
        this.tag_time_list = tag.timeList
        this.tag_time = tag.timeList[0][0]
        this.tag_time_index = 0
        // 操作视频播放器跳到对应位置 文件解析进入到对应位置
        this.player.seek(this.tag_time);
      } else {
        setTimeout(() => {
          var iframe = document.querySelector('#iframe')
          console.log(
            iframe,
            this.$config.VUE_APP_BASE_API,
            'iframe',
            this.activeTag
          )
          this.populateIframe(
            iframe,
            [['token', +localStorage.getItem('token')]],
            this.downloadUrl
          )
        }, 0)
      }
    },
    delTag(uid) {
      this.$confirm('此操作将解除该标签的绑定, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tags.forEach((item, index) => {
          if (item.id === uid) {
            this.tags.splice(index, 1)
          }
        })

        const labelList = this.tags.map((o) => {
          return o.id
        })

        this.$http({
          url: '/knowledgeLabel/bind',
          method: 'post',
          data: {
            knowledgeId: this.$route.query.row.id,
            labelList: labelList
          }
        }).then(({ data }) => {
          if (data.code == 200) {
            this.$message.success('解除绑定成功')
            this.labelListFn(this.dataInfo)
          }
        })
      })
    },
    handlePrev(item, index){
      console.log('item, index',item, index)
      if (index === 0) {
        return true
      }
      this.tag_time_index = index - 1
      this.tag_time = this.tag_time_list[this.tag_time_index][0]
      // 操作视频播放器跳到对应位置 文件解析进入到对应位置
      this.player.seek(this.tag_time);
    },
    handleNext(item, index){
      console.log('item, index',item, index)
      if (index === (this.tag_time_list.length - 1)) {
        return true
      }
      this.tag_time_index = index + 1
      this.tag_time = this.tag_time_list[this.tag_time_index][0]
      // 操作视频播放器跳到对应位置 文件解析进入到对应位置
      this.player.seek(this.tag_time);
    }
  }
}
</script>
<style lang="scss" scoped>
#contianer {
    width: 98%;
    height: 85vh;
    border-radius: 10px;
    background: #fff;
    padding: 20px;
    margin: 1%;
    position: absolute;
    .mapPage {
        // overflow: auto;
        height: 100%;
        .button_tab {
            display: flex;
            justify-content: space-between;
        }
        .main {
            display: flex;
            height: 76vh;
            .file_box {
                flex: 1;
                // width: 50%;
                border-right: 1px solid #d8d8d8;
                #video {
                    flex: auto;
                    height: calc(85vh - 80px) !important;
                    padding-top: 0!important;
                    position: relative;
                }
              .video_btn_img{
                width: 20px;
                height: 60px;
                position: absolute;
                right: 14px;
                top: calc(50% - 30px);
                z-index: 9999;
                overflow: hidden;
                .tag_time{
                  width: 20px;
                  height: 60px;
                  display: flex;
                  flex-direction: column;
                  justify-content: space-between;
                  align-items: center;
                  .disabled{
                    cursor: not-allowed;
                  }
                }
              }
            }
            .video_text_box {
                width: 30%;
                border-right: 1px solid #d8d8d8;
                overflow: auto;
                .box-card {
                    margin-bottom: 10px;
                }
            }
            .tag_box {
                // flex: 1;
                width: 20%;
                padding-left: 10px;
                .tag_item {
                    margin: 10px;
                    cursor: pointer;
                }
                .tag_active {
                    background: #67deb2;
                    color: #fff;
                }
                .tag_list {
                  height: 100%;
                  overflow-y: auto;
                }
            }
        }
        h2 {
            font-size: 20px;
            font-weight: 550;
            display: flex;
            justify-content: space-between;
        }
    }
}
</style>
